package com.jof.framework.hmc.sender.email;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jof.framework.hmc.domain.Email;

/**
 * @author zhangtao
 * 验证邮件对象是否合法
 *
 */
public class EmailVerifyStrategy {

	private static final Logger LOG = LoggerFactory.getLogger(EmailVerifyStrategy.class);

	/**
	 * 附件规则过滤列表
	 */
	private List<EmailAttachmentFilter> filterList;

	/**
	 * 总收件人数量
	 */
	private int totalRecipient;

	public boolean verifyEmail(Email email) {
		//总收件人数量
		int recNum = 0;
		if (email.getToRecipient() != null) {
			recNum = recNum + email.getToRecipient().size();
		}
		if (email.getCcRecipient() != null) {
			recNum = recNum + email.getCcRecipient().size();
		}
		if (email.getBccRecipient() != null) {
			recNum = recNum + email.getBccRecipient().size();
		}
		//验证总数
		if (recNum > totalRecipient) {
			LOG.error("Recipient more than " + totalRecipient + "!");
			return false;
		}
		//验证附件
		if (email.getAttachment() != null && email.getAttachment().size() > 0) {
			//获取附件总大小
			long totLength = 0;
			for (String fileName : email.getAttachment().keySet()) {
				if (email.getAttachment().get(fileName) != null) {
					totLength = totLength + email.getAttachment().get(fileName).length;
				}
			}
			//按规则验证附件
			for (EmailAttachmentFilter eaf : filterList) {
				if (recNum >= eaf.getFrom() && recNum <= eaf.getTo() && totLength > eaf.getLength()) {
					LOG.error("Attachment length more than definition!");
					return false;
				}
			}
		}
		return true;
	}

	public void setFilterList(List<EmailAttachmentFilter> filterList) {
		this.filterList = filterList;
	}

	public void setTotalRecipient(int totalRecipient) {
		this.totalRecipient = totalRecipient;
	}

}
